//
//  RootViewController.m
//  iMoney
//
//  Created by VertigoSol on 9/11/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "RootViewController.h"
#import "Account.h"
#import "ExpenseViewController.h"
#import "AccountCell.h"


@implementation RootViewController
@synthesize ad;


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return  [[self.ad state] numAccounts];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"AccountCell";
    
	AccountCell *cell = (AccountCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		cell = [[[AccountCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; // changed this
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
    
	//get account and set values
	Account* a = [[self.ad state] getAccount:indexPath.row];
	[cell setVals:[a accountName] : [a totalAmount]];
	
    // Set up the cell
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic -- create and push a new view controller
	
	ExpenseViewController* evc = [[ExpenseViewController alloc] initWithAccount:[[ad state] getAccount:indexPath.row]];
	evc.title = [[[[self.ad state] accounts] objectAtIndex:indexPath.row] accountName];
	
	[[self navigationController] pushViewController:evc animated:YES];
	[evc release];
	
}


- (id)initWithStyle:(UITableViewStyle)style {
	
	if (self = [super initWithStyle:UITableViewStyleGrouped]) {
		self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
		//self.tableView.rowHeight = 60;
		
		self.view.frame = CGRectMake(0,100,320,200);
	}
	return self;
}

//view was loaded
- (void)viewDidLoad {
   
	ad = (iMoneyAppDelegate*)[[UIApplication sharedApplication] delegate];

	self.title = @"Accounts";
	
	UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]
								   initWithTitle:@"Options" 
								   style:UIBarButtonItemStylePlain
								   target:self action:@selector(options:)] autorelease];
	
	self.navigationItem.leftBarButtonItem = addButton;

}

//Handle the options
-(void) options:(id)sender {
	
	// open a dialog options
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Options"
															 delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
													otherButtonTitles:@"Add Account",@"Edit Accounts",@"Transfer",@"E-Mail Data", @"About", nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	[actionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table)
	[actionSheet release];

	
}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	
		switch(buttonIndex)
		{
			case 0:  //add account
			{
				UIAlertView *myAlertView = [[UIAlertView alloc] 
											initWithTitle:@"Add an Account" message:@"Account Name?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
				
				UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
				[textField setBackgroundColor:[UIColor whiteColor]];
				[myAlertView addSubview:textField];
				
				//move up
				CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 130.0);
				[myAlertView setTransform:myTransform];
				
				
				[myAlertView show];
				[myAlertView release];
				break;
			}
		
			case 1: //edit accounts
			{
				
				UIBarButtonItem *done = [[[UIBarButtonItem alloc]
											   initWithTitle:@"Done" 
											   style:UIBarButtonItemStyleDone
											   target:self action:@selector(done:)] autorelease];
				
				self.navigationItem.rightBarButtonItem = done;
				[self.tableView setEditing:YES animated:YES];
				break;
			}
				
			case 2: //transfer
			{
				
				break;
			}	
				
			case 3: //email
			{
				//TODO add user pref + body
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:smcgrail@unm.edu"]];			
				break;
			}

			case 4: //about
			{
				NSString* name = [[NSString alloc] initWithString:@"Created by Sean McGrail\nCopyright @2008"];
				
				UIAlertView *myAlertView = [[UIAlertView alloc] 
											initWithTitle:@"About" message:name delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
				
				[myAlertView show];
				[myAlertView release];
				[name release];
				
				break;
			}
				
			case 5: //cancel
			{
				break;
			}	
		}	

			
	
}

-(void) done:(id)sender 
{
	[self.tableView setEditing:NO animated:YES];
	self.navigationItem.rightBarButtonItem = nil;	
}


//uialertview handler
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	NSString* name = [[[alertView subviews] objectAtIndex:4] text];
	Account* acc = [[Account alloc] initWithName:name];
	
	if(![[ad state] containsAccount:name] && [name length] > 0 && buttonIndex ==1)
	{	
		[[ad state] addAccount:acc];
		[self.tableView reloadData];
	}

}




// Override to support editing the list
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
	
		//remove from model
		[[[ad state] accounts] removeObjectAtIndex:indexPath.row];	
		
		 // Delete the row from the data source
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
	
		
    }   
    if (editingStyle == UITableViewCellEditingStyleInsert) {
	
    }   
	
	
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{

		return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(self.tableView.editing)
	{
		return YES;
	}
	else
		return NO;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	[self.tableView reloadData];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[self.tableView release];
	[ad release];
    [super dealloc];
}


@end

